<template>
  <div class="sql-query-container">
    <!-- 左右分栏布局 -->
    <div class="main-layout">
      <!-- 左侧数据库面板 -->
      <div class="left-panel" :class="{ collapsed: leftPanelCollapsed }">
        <div class="panel-header">
          <div class="panel-title">
            <el-icon><Coin /></el-icon>
            <span v-if="!leftPanelCollapsed">数据库实例</span>
          </div>
          <div class="panel-actions">
            <el-button 
              v-if="!leftPanelCollapsed"
              type="primary" 
              size="small" 
              @click="addConnectionDialogVisible = true"
            >
              <el-icon><Plus /></el-icon>
              新建
            </el-button>
            <el-button 
              size="small" 
              @click="refreshDatabases"
              :loading="refreshing"
            >
              <el-icon><Refresh /></el-icon>
            </el-button>
            <el-button 
              size="small" 
              @click="toggleLeftPanel"
              class="collapse-btn"
            >
              <el-icon><ArrowLeft v-if="!leftPanelCollapsed" /><ArrowRight v-else /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 数据库实例列表 -->
        <div class="database-list" v-if="!leftPanelCollapsed">
          <div 
            v-for="db in databases" 
            :key="db.id"
            class="database-item"
            :class="{ 
              active: selectedDatabase === db.id,
              disabled: db.database_type === 'mysql' && !db.database_name
            }"
            @click="selectDatabase(db)"
          >
            <div class="db-icon">
              <el-icon>
                <component :is="getDatabaseIcon(db.database_type)" />
              </el-icon>
            </div>
            <div class="db-content">
              <div class="db-name">{{ db.name }}</div>
              <div class="db-detail">
                <span class="db-type">{{ db.database_type.toUpperCase() }}</span>
                <span class="db-host">{{ db.host }}:{{ db.port }}</span>
              </div>
              <div v-if="db.database_name" class="db-database">
                📁 {{ db.database_name }}
              </div>
              <div v-else-if="db.database_type === 'mysql'" class="db-warning">
                ⚠️ 未指定数据库
              </div>
            </div>
            <div class="db-status">
              <el-icon 
                :class="getConnectionStatusClass(db)"
                :title="getConnectionStatusTitle(db)"
              >
                <component :is="getConnectionStatusIcon(db)" />
              </el-icon>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-if="databases.length === 0" class="empty-state">
            <el-icon><Coin /></el-icon>
            <p>暂无数据库实例</p>
            <el-button type="primary" size="small" @click="addConnectionDialogVisible = true">
              添加连接
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧SQL编辑器面板 -->
      <div class="right-panel">
        <!-- 当前连接状态栏 -->
        <div class="connection-bar" v-if="selectedDatabase">
          <div class="current-connection">
            <el-icon><Link /></el-icon>
            <span>{{ getCurrentDatabase()?.name }}</span>
            <el-tag :type="getDbTypeTag(getCurrentDatabase()?.database_type)" size="small">
              {{ getCurrentDatabase()?.database_type?.toUpperCase() }}
            </el-tag>
          </div>
        </div>

        <!-- SQL编辑器 -->
        <div class="sql-editor-section">
          <div class="editor-header">
            <h3>SQL编辑器</h3>
            <div class="editor-actions">
              <el-button 
                type="primary" 
                @click="executeQuery"
                :loading="executing"
                :disabled="!selectedDatabase || !queryForm.sql_content.trim()"
              >
                <el-icon><CaretRight /></el-icon>
                执行查询
              </el-button>
              <el-button @click="newQuery">
                <el-icon><DocumentAdd /></el-icon>
                新建查询
              </el-button>
            </div>
          </div>

          <!-- SQL编辑器文本框 -->
          <div class="editor-container">
            <el-input
              v-model="queryForm.sql_content"
              type="textarea"
              placeholder="请输入SQL语句..."
              :rows="12"
              class="sql-textarea"
            />
            <div class="editor-info">
              <span>字符数: {{ queryForm.sql_content.length }}</span>
              <span>行数: {{ queryForm.sql_content.split('\n').length }}</span>
            </div>
          </div>
        </div>

        <!-- 查询结果 -->
        <div class="result-section" v-if="queryResult">
          <div class="result-header">
            <h3>查询结果</h3>
            <div class="result-actions">
              <el-button size="small">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </div>

          <div class="result-stats">
            <el-tag>执行时间: {{ queryResult.execution_time }}s</el-tag>
            <el-tag type="success">返回行数: {{ queryResult.row_count }}</el-tag>
            <el-tag type="info">SQL类型: {{ queryResult.sql_type }}</el-tag>
          </div>

          <!-- 结果表格 -->
          <div class="result-table">
            <el-table 
              :data="paginatedResults" 
              border 
              stripe 
              height="300"
              style="width: 100%"
            >
              <el-table-column 
                v-for="(column, index) in queryResult.columns" 
                :key="index"
                :prop="index.toString()"
                :label="column"
                min-width="120"
                show-overflow-tooltip
              >
                <template #default="scope">
                  {{ scope.row[index] }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="result-pagination" v-if="queryResult.rows.length > pageSize">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="queryResult.rows.length"
              layout="total, prev, pager, next, jumper"
              @current-change="handlePageChange"
            />
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-else class="empty-result">
          <el-icon><DocumentCopy /></el-icon>
          <p>请选择数据库实例并输入SQL语句开始查询</p>
        </div>
      </div>
    </div>

    <!-- 新建连接对话框 -->
    <el-dialog
      v-model="addConnectionDialogVisible"
      title="新建数据库连接"
      width="600px"
      @opened="onDialogOpened"
    >
      <el-form
        ref="connectionFormRef"
        :model="connectionForm"
        :rules="connectionRules"
        label-width="120px"
      >
        <el-form-item label="连接名称" prop="name">
          <el-input v-model="connectionForm.name" placeholder="请输入连接名称" />
        </el-form-item>

        <el-form-item label="数据库类型" prop="database_type">
          <el-select 
            v-model="connectionForm.database_type" 
            placeholder="请选择数据库类型"
            @change="handleDatabaseTypeChange"
          >
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="SQLite" value="sqlite" />
            <el-option label="MongoDB" value="mongodb" />
          </el-select>
        </el-form-item>

        <el-form-item label="服务器地址" prop="host">
          <el-input v-model="connectionForm.host" placeholder="如：192.168.1.100" />
        </el-form-item>

        <el-form-item label="端口" prop="port">
          <el-input-number 
            v-model="connectionForm.port" 
            :min="1" 
            :max="65535" 
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="connectionForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="connectionForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item 
          :label="getDatabaseNameLabel()"
          :rules="getDatabaseNameRules()"
        >
          <el-input 
            v-model="connectionForm.database_name" 
            :placeholder="getDatabaseNamePlaceholder()"
          />
          <div class="form-hint">{{ getDatabaseNameHint() }}</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addConnectionDialogVisible = false">取消</el-button>
          <el-button @click="testConnectionBeforeSave" :loading="testingConnection">
            测试连接
          </el-button>
          <el-button type="primary" @click="saveConnection" :loading="savingConnection">
            保存连接
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Coin, Plus, Refresh, ArrowLeft, ArrowRight, Link, CaretRight,
  DocumentAdd, Download, DocumentCopy, Monitor, Server, HardDrive,
  CircleCheck, CircleClose, Warning, Files, Folder
} from '@element-plus/icons-vue'
import { sqlAPI } from '@/api/sql'

// 响应式数据
const leftPanelCollapsed = ref(false)
const refreshing = ref(false)
const databases = ref([])
const selectedDatabase = ref(null)
const executing = ref(false)
const queryResult = ref(null)
const currentPage = ref(1)
const pageSize = ref(100)

// 表单数据
const queryForm = ref({
  sql_content: ''
})

// 连接对话框
const addConnectionDialogVisible = ref(false)
const connectionFormRef = ref(null)
const testingConnection = ref(false)
const savingConnection = ref(false)

const connectionForm = ref({
  name: '',
  database_type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: '',
  password: '',
  database_name: ''
})

// 默认端口配置
const defaultPorts = {
  mysql: 3306,
  postgresql: 5432,
  sqlserver: 1433,
  oracle: 1521,
  sqlite: 0,
  mongodb: 27017
}

// 数据库类型配置
const databaseTypeConfig = {
  mysql: {
    required: false,
    placeholder: '请输入数据库名称（可选）',
    hint: '可选项：可以只连接服务器后再选择具体数据库',
    defaultValue: '',
    label: '数据库名称'
  },
  postgresql: {
    required: false,
    placeholder: '如：postgres',
    hint: '可选项：建议填写默认数据库名"postgres"',
    defaultValue: 'postgres',
    label: '数据库名称'
  },
  sqlserver: {
    required: true,
    placeholder: '如：master',
    hint: '必填项：SQL Server需要指定数据库名称',
    defaultValue: 'master',
    label: '数据库名称'
  },
  oracle: {
    required: true,
    placeholder: '如：ORCL',
    hint: '必填项：请输入Oracle服务名或SID',
    defaultValue: '',
    label: '服务名/SID'
  },
  sqlite: {
    required: true,
    placeholder: '如：/path/to/database.db',
    hint: '必填项：请输入SQLite数据库文件的完整路径',
    defaultValue: '',
    label: '数据库文件路径'
  },
  mongodb: {
    required: false,
    placeholder: '如：myapp',
    hint: '可选项：MongoDB数据库名称',
    defaultValue: '',
    label: '数据库名称'
  }
}

// 表单验证规则
const connectionRules = {
  name: [
    { required: true, message: '请输入连接名称', trigger: 'blur' }
  ],
  database_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 计算属性
const paginatedResults = computed(() => {
  if (!queryResult.value || !queryResult.value.rows) return []
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return queryResult.value.rows.slice(start, end)
})

// 获取当前数据库
const getCurrentDatabase = () => {
  return databases.value.find(db => db.id === selectedDatabase.value)
}

// 获取数据库类型标签
const getDbTypeTag = (type) => {
  const typeMap = {
    mysql: 'success',
    postgresql: 'info',
    sqlserver: 'warning',
    oracle: 'danger',
    sqlite: '',
    mongodb: 'success'
  }
  return typeMap[type?.toLowerCase()] || 'info'
}

// 获取数据库图标
const getDatabaseIcon = (type) => {
  const iconMap = {
    mysql: Coin,
    postgresql: Coin,
    sqlserver: Server,
    oracle: HardDrive,
    sqlite: HardDrive,
    mongodb: Coin
  }
  return iconMap[type?.toLowerCase()] || Coin
}

// 获取连接状态图标
const getConnectionStatusIcon = (db) => {
  if (db.database_type === 'mysql' && !db.database_name) {
    return Warning
  }
  return CircleCheck
}

// 获取连接状态样式
const getConnectionStatusClass = (db) => {
  if (db.database_type === 'mysql' && !db.database_name) {
    return 'status-warning'
  }
  return 'status-success'
}

// 获取连接状态标题
const getConnectionStatusTitle = (db) => {
  if (db.database_type === 'mysql' && !db.database_name) {
    return '需要配置数据库名称'
  }
  return '连接配置正常'
}

// 数据库名称相关方法
const getDatabaseNameLabel = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.label : '数据库名称'
}

const getDatabaseNamePlaceholder = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.placeholder : '请输入数据库名称'
}

const getDatabaseNameHint = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  return config ? config.hint : ''
}

const getDatabaseNameRules = () => {
  const config = databaseTypeConfig[connectionForm.value.database_type]
  if (config && config.required) {
    return [
      { required: true, message: `请输入${config.label}`, trigger: 'blur' }
    ]
  }
  return []
}

// 主要方法
// 切换左侧面板
const toggleLeftPanel = () => {
  leftPanelCollapsed.value = !leftPanelCollapsed.value
}

// 选择数据库
const selectDatabase = (db) => {
  if (db.database_type === 'mysql' && !db.database_name) {
    ElMessage.warning('该数据库实例未配置数据库名称，无法使用')
    return
  }
  selectedDatabase.value = db.id
  queryResult.value = null
}

// 加载数据库列表
const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    console.log('API响应:', response)

    // 由于axios拦截器返回response.data，所以直接处理response
    let data = []
    if (response) {
      if (response.results) {
        // 分页响应格式
        data = response.results
      } else if (Array.isArray(response)) {
        // 直接数组格式
        data = response
      } else if (response.data && Array.isArray(response.data)) {
        // 嵌套data格式
        data = response.data
      }
    }

    databases.value = data
    console.log('加载的数据库列表:', databases.value)
  } catch (error) {
    console.error('加载数据库失败:', error)
    ElMessage.error(`加载数据库失败: ${error.response?.data?.error || error.message}`)
  }
}

// 刷新数据库列表
const refreshDatabases = async () => {
  try {
    refreshing.value = true
    await loadDatabases()
    ElMessage.success('数据库列表已刷新')
  } catch (error) {
    ElMessage.error('刷新数据库列表失败')
  } finally {
    refreshing.value = false
  }
}

// 数据库类型变化时更新默认端口和数据库名称
const handleDatabaseTypeChange = (type) => {
  const newPort = defaultPorts[type] || 3306
  connectionForm.value.port = newPort

  // 根据数据库类型设置默认数据库名称
  const config = databaseTypeConfig[type]
  if (config && config.defaultValue) {
    connectionForm.value.database_name = config.defaultValue
  } else {
    connectionForm.value.database_name = ''
  }

  // 强制更新视图
  nextTick(() => {
    if (connectionFormRef.value) {
      connectionFormRef.value.clearValidate()
    }
  })
}

// 对话框打开时的处理
const onDialogOpened = () => {
  nextTick(() => {
    if (connectionFormRef.value) {
      connectionFormRef.value.clearValidate()
    }

    // 确保端口字段显示正确的默认值
    const currentType = connectionForm.value.database_type
    if (currentType) {
      handleDatabaseTypeChange(currentType)
    }
  })
}

// 测试连接
const testConnectionBeforeSave = async () => {
  try {
    await connectionFormRef.value.validate()
    testingConnection.value = true

    console.log('开始测试连接，参数:', connectionForm.value)

    // 直接调用测试连接API，传递连接参数
    const response = await sqlAPI.testConnectionWithParams(connectionForm.value)

    console.log('API响应:', response)

    // 由于axios拦截器返回response.data，所以直接访问response的属性
    if (response && response.success) {
      ElMessage.success(`连接测试成功！连接时间: ${response.connection_time}s`)
      if (response.version) {
        ElMessage.info(`数据库版本: ${response.version}`)
      }
    } else {
      const errorMessage = response?.message || '连接测试失败'
      ElMessage.error(`连接测试失败: ${errorMessage}`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)

    // 改进错误处理
    let errorMessage = '连接测试失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
  } finally {
    testingConnection.value = false
  }
}

// 保存连接
const saveConnection = async () => {
  try {
    await connectionFormRef.value.validate()
    savingConnection.value = true

    await sqlAPI.createDatabaseInstance(connectionForm.value)

    ElMessage.success('数据库连接创建成功')
    addConnectionDialogVisible.value = false
    loadDatabases()
  } catch (error) {
    console.error('创建连接失败:', error)
    ElMessage.error('创建连接失败: ' + (error.response?.data?.error || error.message))
  } finally {
    savingConnection.value = false
  }
}

// 执行SQL查询
const executeQuery = async () => {
  if (!selectedDatabase.value || !queryForm.value.sql_content.trim()) {
    ElMessage.warning('请选择数据库实例并输入SQL语句')
    return
  }

  // 检查选择的数据库实例是否有数据库名称
  const currentDb = getCurrentDatabase()
  if (currentDb && currentDb.database_type === 'mysql' && !currentDb.database_name) {
    ElMessage.warning('所选数据库实例未指定数据库名称，请选择已配置数据库名称的实例或重新配置该实例')
    return
  }

  executing.value = true
  try {
    console.log('执行查询，参数:', {
      database_id: selectedDatabase.value,
      sql_content: queryForm.value.sql_content,
      limit: 1000
    })

    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: queryForm.value.sql_content,
      limit: 1000
    })

    console.log('查询响应:', response)

    // 由于axios拦截器返回response.data，所以直接访问response的属性
    if (response && response.result) {
      queryResult.value = response.result
      currentPage.value = 1

      const message = response.message || '查询执行成功'
      ElMessage.success(message)
    } else {
      throw new Error('响应数据格式错误')
    }
  } catch (error) {
    console.error('查询执行失败:', error)

    // 改进错误处理
    let errorMessage = '查询执行失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    } else if (error.error) {
      errorMessage = error.error
    } else if (error.message) {
      errorMessage = error.message
    }

    ElMessage.error(errorMessage)
    queryResult.value = null
  } finally {
    executing.value = false
  }
}

// 新建查询
const newQuery = () => {
  queryForm.value.sql_content = ''
  queryResult.value = null
  ElMessage.success('已清空编辑器')
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

// 组件挂载时加载数据
onMounted(() => {
  loadDatabases()
})
</script>

<style scoped>
.sql-query-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-layout {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
}

/* 左侧面板 */
.left-panel {
  width: 300px;
  background: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}

.left-panel.collapsed {
  width: 60px;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.collapse-btn {
  padding: 8px !important;
}

.database-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.database-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.database-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.database-item.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.database-item.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.database-item.disabled:hover {
  border-color: #e4e7ed;
  box-shadow: none;
}

.db-icon {
  margin-right: 12px;
  color: #409eff;
}

.db-content {
  flex: 1;
  min-width: 0;
}

.db-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  display: block;
}

.db-detail {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 8px;
}

.db-type {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

.db-database {
  font-size: 12px;
  color: #67c23a;
  margin-top: 4px;
}

.db-warning {
  font-size: 12px;
  color: #e6a23c;
  margin-top: 4px;
}

.db-status {
  margin-left: 8px;
}

.status-success {
  color: #67c23a;
}

.status-warning {
  color: #e6a23c;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.connection-bar {
  padding: 12px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.current-connection {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.sql-editor-section {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.editor-header h3 {
  margin: 0;
  color: #303133;
}

.editor-actions {
  display: flex;
  gap: 12px;
}

.editor-container {
  position: relative;
}

.sql-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.editor-info {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.result-section {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-header h3 {
  margin: 0;
  color: #303133;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.result-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.result-table {
  flex: 1;
  overflow: hidden;
}

.result-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.empty-result {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.empty-result .el-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 250px;
  }
}

@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 200px;
  }

  .left-panel.collapsed {
    height: 60px;
  }
}
</style>
